package com.dhcc.cdc.busi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.dao.CdcPatientMapper;
import com.dhcc.cdc.busi.dao.CdcUserMapper;
import com.dhcc.cdc.busi.entity.CdcPatientEntity;
import com.dhcc.cdc.busi.entity.CdcUserEntity;
import com.dhcc.cdc.busi.service.ICdcPatientService;
import com.dhcc.cdc.sys.dao.CdcDataMapper;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 患者主信息表数据服务层接口
 * 
 * @ClassName: CdcPatientServiceImpl
 * @Description: TODO
 * @author jumper
 * @date 2021-03-15 10:20:07
 */
@Service("cdcPatientService")
public class CdcPatientServiceImpl extends BaseServiceImpl<CdcPatientMapper, CdcPatientEntity> implements ICdcPatientService {
	@Autowired
	private CdcUserMapper cdcUserMapper;
	@Autowired
	private CdcDataMapper cdcDataMapper;

	@Override
	public List<CdcPatientEntity> page(Page<CdcPatientEntity> page, Map<String, Object> map) {
		return this.baseMapper.page(page, map);
	}
	@Override
	public List<CdcPatientEntity> list(Map<String, Object> map) {
		return this.baseMapper.list(map);
	}
    @Override
    public CdcPatientEntity getByCode(String patientCode) {
        return this.baseMapper.getByCode(patientCode);
    }
    /**
     * 
     * <p>Title: handleXmlData</p>   
     * <p>Description: </p>   
     * @param dataStr
     * @return   
     * @see com.dhcc.cdc.busi.service.ICdcPatientService#handleXmlData(java.lang.String)   
     *
     */
	@Override
	public String handleXmlData(String dataStr) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Document doc = null;
        try {
            doc = DocumentHelper.parseText(dataStr); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            String patientcode= rootElt.elementTextTrim("patientcode"); //患者主索引
            String healthcode= rootElt.elementTextTrim("healthcode"); //电子健康码
            String name= rootElt.elementTextTrim("name"); //姓名
            String gender= rootElt.elementTextTrim("gender"); //性别
            String nationality= rootElt.elementTextTrim("nationality"); //国籍
            String nation= rootElt.elementTextTrim("nation"); //民族
            String birthdatestr= rootElt.elementTextTrim("birthdate"); //出生日期
            String agestr= rootElt.elementTextTrim("age"); //年龄
            String agemonthstr= rootElt.elementTextTrim("agemonth"); //年龄月
            String agedaystr= rootElt.elementTextTrim("ageday"); //年龄天
            String cardtype= rootElt.elementTextTrim("cardtype"); //证件类型
            String cardvalue= rootElt.elementTextTrim("cardvalue"); //证件号码
            String nativeplace= rootElt.elementTextTrim("nativeplace"); //籍贯
            String nativeaddress= rootElt.elementTextTrim("nativeaddress"); //户籍所在地详细描述
            String nowaddress= rootElt.elementTextTrim("nowaddress"); //现住址详细描述
            String company= rootElt.elementTextTrim("company"); //工作单位
            String telephone= rootElt.elementTextTrim("telephone"); //电话
            String email= rootElt.elementTextTrim("email"); //邮箱
            String contactor= rootElt.elementTextTrim("contactor"); //联系人
            String contactorphone= rootElt.elementTextTrim("contactorphone"); //联系人电话
            String career= rootElt.elementTextTrim("career"); //职业
            String bloodabo= rootElt.elementTextTrim("bloodabo"); //血型ABO
            String bloodrh= rootElt.elementTextTrim("bloodrh"); //血型Rh
            String updatetimestr= rootElt.elementTextTrim("updatetime"); //更新时间
            String updateuserid= rootElt.elementTextTrim("updateuserid"); //更新人
            String opercode= rootElt.elementTextTrim("opercode"); //操作码
            
            CdcPatientEntity patient = new CdcPatientEntity();
            patient.setPatientCode(patientcode);//患者主索引
            //获取dataid
        	CdcDataEntity cdcDataEntity = new CdcDataEntity();
        	cdcDataEntity.setCode("PatData");
        	cdcDataEntity.setIsActive(1);
        	cdcDataEntity = cdcDataMapper.selectOne(cdcDataEntity);
    		Long dataId = cdcDataEntity.getId();
			//获取dataid
			CdcDataEntity cdcDataEntityBase = new CdcDataEntity();
			cdcDataEntityBase.setCode("HisBase");
			cdcDataEntityBase.setIsActive(1);
			cdcDataEntityBase = cdcDataMapper.selectOne(cdcDataEntityBase);
    		Long basedataId = cdcDataEntityBase.getId();
    		//更新时间
    		if(CommonUtil.isNotEmpty(updatetimestr)) {
        		Date updatetime = sdf.parse(updatetimestr);
        		patient.setUpdateDate(updatetime);
        	}
        	//获取更新人
        	if(CommonUtil.isNotEmpty(updateuserid)) {
        		CdcUserEntity cdcUserEntity = new CdcUserEntity();
        		cdcUserEntity.setXcode(updateuserid);
        		cdcUserEntity.setDataId(basedataId);
        		cdcUserEntity.setIsActive(1);
        		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
        		//判断人员存在不存在
        		Long updateuser = null;
        		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
        			cdcUserEntity = new CdcUserEntity();
        			cdcUserEntity.setXcode(updateuserid);
            		cdcUserEntity.setIsActive(1);
        			cdcUserEntity.setCode("newuser"+updateuserid);
        			cdcUserEntity.setName("newuser"+updateuserid);
            		cdcUserEntity.setDataId(basedataId);
            		//保存用户
            		cdcUserMapper.insert(cdcUserEntity);
            		updateuser = cdcUserEntity.getId();
        		}else {
        			updateuser = cdcUserEntity.getId();
        		}
        		patient.setUpdateBy(updateuser);
        	}
            if("1".equals(opercode)) {//保存/修改
            	if(CommonUtil.isNotEmpty(healthcode)) {
            		patient.setHealthCode(healthcode);
            	}
            	if(CommonUtil.isNotEmpty(name)) {
            		patient.setName(name);
            	}
            	if(CommonUtil.isNotEmpty(gender)) {
            		patient.setGender(gender);
            	}
            	if(CommonUtil.isNotEmpty(nationality)) {
            		patient.setNationality(nationality);
            	}
            	if(CommonUtil.isNotEmpty(nation)) {
            		patient.setNation(nation);
            	}
            	if(CommonUtil.isNotEmpty(birthdatestr)) {
            		Date birthdate = sdf.parse(birthdatestr);
            		patient.setBirthdate(birthdate);
            	}
                if(CommonUtil.isNotEmpty(agestr)) {
            		Integer age = Integer.valueOf(agestr);
            		patient.setAge(age);
            	}
                if(CommonUtil.isNotEmpty(agemonthstr)) {
            		Integer agemonth = Integer.valueOf(agemonthstr);
            		patient.setAgeMonth(agemonth);
            	}
                if(CommonUtil.isNotEmpty(agedaystr)) {
            		Integer ageday = Integer.valueOf(agedaystr);
            		patient.setAgeDay(ageday);
            	}
                if(CommonUtil.isNotEmpty(cardtype)) {
                	patient.setCardType(cardtype);
            	}
            	if(CommonUtil.isNotEmpty(cardvalue)) {
            		patient.setCardValue(cardvalue);
            	}
            	if(CommonUtil.isNotEmpty(nativeplace)) {
            		patient.setNativePlace(nativeplace);
             	}
             	if(CommonUtil.isNotEmpty(nativeaddress)) {
             		patient.setNativeAddress(nativeaddress);
             	}
             	 if(CommonUtil.isNotEmpty(nowaddress)) {
             		patient.setNowAddress(nowaddress);
             	}
             	if(CommonUtil.isNotEmpty(company)) {
             		patient.setCompany(company);
             	}
             	 if(CommonUtil.isNotEmpty(telephone)) {
             		patient.setTelephone(telephone);
             	}
             	if(CommonUtil.isNotEmpty(email)) {
             		patient.setEmail(email);
             	}
             	 if(CommonUtil.isNotEmpty(contactor)) {
             		patient.setContactor(contactor);
             	}
             	if(CommonUtil.isNotEmpty(contactorphone)) {
             		patient.setContactorPhone(contactorphone);
             	}
             	if(CommonUtil.isNotEmpty(career)) {
             		patient.setCareer(career);
             	}
            	patient.setDataId(dataId);
            	if(CommonUtil.isNotEmpty(bloodabo)) {
            		patient.setBloodAbo(bloodabo);
             	}
            	if(CommonUtil.isNotEmpty(bloodrh)) {
            		patient.setBloodRh(bloodrh);
             	}
            	patient.setIsActive(1);
            }else {//逻辑删除
            	patient.setIsActive(0);
            }
            //先判断是不是有该对象
            Wrapper<CdcPatientEntity> wrapper =  new EntityWrapper<CdcPatientEntity>();
            wrapper.eq("patient_code", patient.getPatientCode());//患者代码
            wrapper.eq("data_id", dataId);//元数据ID
            int count = this.selectCount(wrapper);
            if(count>0) {
            	this.update(patient, wrapper);
            }else {
            	this.insert(patient);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        } catch (Exception e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        }
		return "<response><status>1</status><message>ok</message></response>";
	}

}